package com.itcast.com.itcast;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.http.HttpResponse;
import com.itcast.constant.MessageConstant;
import com.itcast.constant.RedisMessageConstant;
import com.itcast.entity.Result;
import com.itcast.pojo.Member;
import com.itcast.service.MemberService;
import com.itcast.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 登录验证，不是会员自动注册会员
     * @param map
     * @return 登录信息
     */
    @RequestMapping("/check")
    public Result Check(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String) map.get("telephone");
        telephone = telephone.trim();
        if (telephone!=null&&telephone.length()>0&&
                !"null".equalsIgnoreCase(telephone)){
            String vaildateCode4Login =
                    jedisPool.getResource().get(
                        telephone + RedisMessageConstant.SENDTYPE_LOGIN);
            String validateCode = (String) map.get("validateCode");
            if (vaildateCode4Login!=null&&
                    validateCode!=null&&
                    vaildateCode4Login.equals(validateCode)){
                Member member =
                        memberService.fingMemberByTelephone(telephone);
                if (member==null){
                    member= new Member();
                    member.setPhoneNumber(telephone);
                    String password = member.getPassword();
                    if (password!=null&&password.length()>0){

                    member.setPassword(MD5Utils.md5(password));
                    }
                    memberService.add(member);
                }
                Cookie cookie = new Cookie("telephone", telephone);
                cookie.setMaxAge(60*30);
                cookie.setPath("/");
                response.addCookie(cookie);
                String json = JSON.toJSON(member).toString();
                jedisPool.getResource().setex("jsonCookie",60*30,json);
                return new Result(
                        true,MessageConstant.LOGIN_SUCCESS);
            }
            return new Result(false, "登录失败");
        }
        return new Result(false, "登录失败");
    }

}
